<template>
  <div class="default-tinymce">
    <textarea :id="id"></textarea>
  </div>
</template>
<script>
// import tinymce from 'tinymce/tinymce' //tinymce默认hidden，
// import 'tinymce/themes/silver/theme' //编辑器主题
import { uploadFile } from "@/api/common";

let EDITOR = null;
export default {
  props: {
    value: {
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      id: "editor-" + new Date().getMilliseconds(),
    };
  },
  watch: {
    value(val, oldVal) {
      if (EDITOR && val !== oldVal && val !== EDITOR.getContent()) {
        EDITOR.setContent(val || "");
      }
    },
    disabled(val, oldVal) {
      this.setReadonly();
    },
  },
  methods: {
    setReadonly() {
      if (this.disabled) {
        EDITOR.mode.set("readonly", true);
      }else{
        EDITOR.mode.set("design", true);
      }
    },
  },
  destroyed() {
    // 销毁实例
    if (EDITOR) {
      EDITOR.destroy();
      EDITOR = null;
    }
  },
  mounted() {
    const images_upload_handler = (blobInfo, process) =>
      new Promise((resolve, reject) => {
        const blob = blobInfo.blob();

        const formData = new FormData();
        formData.append("file", blob, blobInfo.fileName);

        uploadFile(formData)
          .then(({ returnObj, success: succ }) => {
            if (succ) {
              // https://nongmao.obs.cn-north-4.myhuaweicloud.com/331834258372415488.png?x-image-process=style/style-list
              // resolve(`/nongmao/nb-as/1.0.1/FileService/previewFile?fileId=${returnObj}`);
              // style-list style-card
              resolve(
                `https://nongmao.obs.cn-north-4.myhuaweicloud.com/${returnObj}?x-image-process=style/style-card`
              );
            } else {
              reject();
            }
          })
          .catch((e) => {
            console.log(e);
            reject(e);
          });
      });

    let self = this;
    tinymce.init({
      selector: `#${this.id}`,
      language_url: "/tinymce/langs/zh_CN.js",
      paste_data_images: true,
      language: "zh_CN",
      // document_base_url:'/',
      // baseURL:'/',
      // convert_urls:false,
      // 自定义url转换方法 否则编辑器会转换图片url地址前缀
      urlconverter_callback: (url, node, on_save, name) => {
        return url;
      },
      // content_style:"img{width:100%}",
      // menubar:false,
      // menubar: "file format table view",
      menu: {
        file: { title: "文件", items: "newdocument" },
        edit: {
          title: "编辑",
          items: "undo redo | cut copy paste pastetext | selectall",
        },
        insert: { title: "插入", items: "link media | template hr | image" },
        view: { title: "查看", items: "visualaid" },
        format: {
          title: "格式",
          items:
            "bold italic underline strikethrough superscript subscript | formats | removeformat",
        },
        table: {
          title: "表格",
          items: "inserttable tableprops deletetable | cell row column",
        },
        tools: { title: "工具", items: "spellchecker code" },
      },
      plugins: "image",
      // image_advtab: true,
      // plugins: [
      //     'advlist autolink lists link image charmap print preview anchor textcolor',
      //     'searchreplace visualblocks code fullscreen',
      //     'insertdatetime table contextmenu paste code wordcount'
      // ],
      images_upload_handler: images_upload_handler,
      init_instance_callback: function (editor) {
        EDITOR = editor;
        EDITOR.setContent(self.value);
        editor.on("input change undo redo paste", (e) => {
          var content = tinymce.activeEditor.getContent() || "";

          self.$emit("input", content);
        });

        self.setReadonly();
      },
    });
  },
};
</script>

<style scoped lang="scss">
.default-tinymce {
  width: 100%;
}
</style>
<style>
.tox-tinymce-aux {
  z-index: 10086 !important;
}
</style>
